package cn.mesmile.gateway.filter;

import cn.hutool.core.util.StrUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zb
 * @version 1.0
 * @date 2020/10/25 14:50
 * @description
 */
//@Component
public class UserGlobalFilter implements GlobalFilter, Ordered {

    /**
     *     【网关不要加入太多业务逻辑，否则会影响性能】
     *
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 写业务逻辑
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        // 根据业务鉴权
        if (StrUtil.isEmpty(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            Mono<Void> voidMono = exchange.getResponse().setComplete();
            return voidMono;
        }
        // 继续往下执行
        Mono<Void> filter = chain.filter(exchange);
        return filter;
    }

    // 数字越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }


}
